package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnlikeBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.model.behavior.dto.UnLikesBehaviorDto;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.behavior.pojo.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojo.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikeBehaviorMapper, ApUnlikesBehavior> implements ApUnlikesBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Override
    public ResponseResult findUnLikeByArticleIdAndEntryId(UnLikesBehaviorDto dto) {
        //1.检验参数

        ApUser user = AppThreadLocalUtils.getUser();
        if (user ==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.查询行为实体
        ApBehaviorEntry apBehaviorEntry = this.apBehaviorEntryService.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry ==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.根据行为实体查询行为
        ApUnlikesBehavior apunlikesBehavior = this.getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));
        if (apunlikesBehavior==null){
            //不喜欢
            apunlikesBehavior = new ApUnlikesBehavior();
            apunlikesBehavior.setEntryId(apBehaviorEntry.getId());
            apunlikesBehavior.setArticleId(dto.getArticleId());
            apunlikesBehavior.setType(dto.getType());
            apunlikesBehavior.setCreatedTime(new Date());
            this.save(apunlikesBehavior);
        }else{
            //取消不喜欢
            this.remove(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                    .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                    .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));
        }
        return ResponseResult.okResult();
    }
}
